import { defineStore } from 'pinia'
import { ref } from 'vue'
import { aiSolverApi, type AiSolverResponse } from '@/api/ai-solver'

export interface ConversationHistory {
  id: string
  question: string
  answer: string
  timestamp: Date
  questionType?: string
  imageUrl?: string
  conversationId: string
}

export const useAiSolverStore = defineStore('aiSolver', () => {
  // 对话历史
  const conversationHistory = ref<ConversationHistory[]>([])
  
  // 当前对话ID
  const currentConversationId = ref('')
  
  // 是否正在加载
  const isLoading = ref(false)

  // 添加对话记录
  const addConversation = (question: string, response: AiSolverResponse, questionType?: string, imageUrl?: string) => {
    const conversation: ConversationHistory = {
      id: response.messageId || `conv_${Date.now()}`,
      question,
      answer: response.answer,
      timestamp: new Date(),
      questionType,
      imageUrl,
      conversationId: response.conversationId || currentConversationId.value
    }
    
    conversationHistory.value.unshift(conversation)
    
    // 限制历史记录数量
    if (conversationHistory.value.length > 50) {
      conversationHistory.value = conversationHistory.value.slice(0, 50)
    }
    
    // 保存到本地存储
    saveToLocalStorage()
  }

  // 清除对话历史
  const clearHistory = () => {
    conversationHistory.value = []
    currentConversationId.value = ''
    saveToLocalStorage()
  }

  // 删除特定对话
  const removeConversation = (id: string) => {
    const index = conversationHistory.value.findIndex(conv => conv.id === id)
    if (index > -1) {
      conversationHistory.value.splice(index, 1)
      saveToLocalStorage()
    }
  }

  // 获取用户对话ID
  const getUserConversationId = async (userId: number) => {
    try {
      const response = await aiSolverApi.getUserConversation(userId)
      currentConversationId.value = response.conversationId || ''
      return response.conversationId
    } catch (error) {
      console.error('获取用户对话ID失败:', error)
      return null
    }
  }

  // 清除用户对话
  const clearUserConversation = async (userId: number) => {
    try {
      await aiSolverApi.clearUserConversation(userId)
      currentConversationId.value = ''
      clearHistory()
    } catch (error) {
      console.error('清除用户对话失败:', error)
    }
  }

  // 保存到本地存储
  const saveToLocalStorage = () => {
    try {
      localStorage.setItem('ai-solver-history', JSON.stringify(conversationHistory.value))
    } catch (error) {
      console.error('保存对话历史失败:', error)
    }
  }

  // 从本地存储加载
  const loadFromLocalStorage = () => {
    try {
      const stored = localStorage.getItem('ai-solver-history')
      if (stored) {
        const parsed = JSON.parse(stored)
        conversationHistory.value = parsed.map((conv: any) => ({
          ...conv,
          timestamp: new Date(conv.timestamp)
        }))
      }
    } catch (error) {
      console.error('加载对话历史失败:', error)
    }
  }

  // 搜索对话历史
  const searchHistory = (query: string) => {
    if (!query.trim()) return conversationHistory.value
    
    const lowerQuery = query.toLowerCase()
    return conversationHistory.value.filter(conv => 
      conv.question.toLowerCase().includes(lowerQuery) ||
      conv.answer.toLowerCase().includes(lowerQuery)
    )
  }

  // 按类型筛选对话
  const filterByType = (type: string) => {
    if (!type) return conversationHistory.value
    return conversationHistory.value.filter(conv => conv.questionType === type)
  }

  return {
    conversationHistory,
    currentConversationId,
    isLoading,
    addConversation,
    clearHistory,
    removeConversation,
    getUserConversationId,
    clearUserConversation,
    loadFromLocalStorage,
    searchHistory,
    filterByType
  }
})
